<template>
    <div class="header-box">
        <div class="block">
            <div class="block-header">
                <div class="block-title">账户余额</div>
                <div class="block-more point" @click="
                    $router.push({
                        path: '/insure/bill'
                    })
                    ">
                    <div class="">查看账单</div>
                    <div class="triangle"></div>
                </div>
            </div>
            <div class="block-content ">
                <div class="row">
                    <div class="">
                        <div class="key">余额（元）</div>
                        <div class="balance">
                            ￥<span class="number">{{ balanceObj.accountBalance }}</span>
                        </div>
                    </div>
                    <img class="img-chart" src="../assets/chart/chart-bar-blue.png"/>
                </div>
                <button class="mini-btn recharge-btn" @click="daycz">充值</button>
            </div>
        </div>
        <div class="block ">
            <div class="block-header">
                <div class="block-title">在保人数</div>
                <div class="block-more point" @click="
                    $router.push({
                        path: '/insure-worker/1'
                    })
                    ">
                    <div class="">查看详情</div>
                    <div class="triangle"></div>
                </div>
            </div>
            <div class="block-content">
                <div class="row">
                    <div class="">
                        <div class="key">人数</div>
                        <div class="number">
                            {{ balanceObj.allEnsureCount }}
                        </div>
                    </div>
                    <img class="img-chart" src="../assets/chart/chart-line-green.png"/>
                </div>
                <div class="align-items compare-box">
                    <img v-if="balanceObj.escalating < 0" src="../assets/decline.png" class="decline-img" alt=""/>
                    <img v-else src="../assets/increase.png" class="decline-img" alt=""/>
                    <div :class="[
                        'font-base',
                        balanceObj.escalating < 0 ? 'color-green' : 'color-red'
                    ]">
                        相比昨天{{ balanceObj.escalating >= 0 ? '提升' : '下降' }}
                        {{ balanceObj.escalating }}%
                    </div>
                </div>
            </div>
        </div>
        <div class="block">
            <div class="block-header block-header-active">
                <div class="block-title">便捷导航</div>
                <div class="block-more">
                    <!-- <div class="">查看详情</div> -->
                    <!-- <div class="triangle"></div> -->
                </div>
            </div>
            <div class="block-content block-content-active row nav">
                <div v-if="isGsc && !canttb" class="nav-item point" @click="onCheckStatusWesure">
                    <img src="../assets/long-insure/batch.png" class="icon-img"/>
                    <div>批量投保</div>
                </div>
                <div v-if="isGsc && canttb" class="nav-item point" @click="cantonCheckStatusWesure">
                    <img src="../assets/long-insure/cantbatch.png" class="icon-img"/>
                    <div>批量投保</div>
                </div>
                <!-- $router.push({
                            path: '/insure/company'
                        }) -->
                <!-- @click="onDialogVisible" 添加派遣单位弹窗 需要引入 派遣单位页面 -->
                <div class="nav-item point" @click="onDialogVisible">
                    <img src="../assets/long-insure/dispatch.png" class="icon-img"/>
                    <div>添加派遣单位</div>
                </div>
                <!-- @click="
                        $router.push({
                            path: '/insure-report'
                        })
                    " -->
                <div class="nav-item point" @click="
                    $router.push({
                        path: '/insure-report'
                    })
                    ">
                    <img src="../assets/long-insure/report.png" class="icon-img"/>
                    <div>报案理赔</div>
                </div>
            </div>
        </div>
    </div>
    <div class="container block block-alone">
        <el-tabs model-value="detail">
            <div class="header">
                <div class="row header-info-box">
                    <div class="title">投保扣费记录</div>
                    <div class="insure-record">
                        <div class="record-i">
                            投保次数：
                            <span class="num">{{ insureCount.insureProjectCount }}</span>
                            次
                        </div>
                        <div class="record-i">
                            投保人次：
                            <span class="num">{{ insureCount.policyPeopleCount }}</span>
                            次
                        </div>
                        <div class="record-i">
                            费用总计：
                            <span class="num">{{ insureCount.amount }}</span>
                            元
                        </div>
                    </div>
                </div>
            </div>
            <div class="row screen-box">
                <div class="search">
                    <el-date-picker v-model="projectTime" type="daterange" class="date-solt point" unlink-panels
                                    range-separator="至" start-placeholder="生效日期" end-placeholder="截止日期"
                                    format="YYYY-MM-DD"
                                    value-format="YYYY-MM-DD" style="width:241px;
                        margin-right:20px"/>
                    <input type="text" placeholder="请输入派遣单位名称" class="input search-input" v-model="searchText"
                           @keydown.enter="search"/>
                    <button class="btn" @click="search">搜索</button>
                    <button class="btn-white" @click="onReset">重置</button>
                </div>
                <div class="align-items">
                    <!-- <div v-if="isGsc">
                        <button class="btn-green" @click="isInsure = true">
                            <i class="el-icon el-icon-document-add" />
                            导入名单
                        </button>
                    </div> -->
                    <div class="search">
                        <!--                        <el-button class="btn-alone" @click="onExportDetail">-->
                        <!--                            <i class="el-icon el-icon-upload2" />导出明细-->
                        <!--                        </el-button>-->
                        <!--                        <button class="btn" @click="onExport">-->
                        <!--                            <i class="el-icon el-icon-upload2" />-->
                        <!--                            导出-->
                        <!--                        </button>-->
                        <export-button style="width: initial" @export="onExportDetail">导出明细</export-button>
                        <export-button @export="onExport"></export-button>
                    </div>
                </div>
            </div>
            <div class="table">
                <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#FBFBFD' }"
                          :header-row-style="{ color: '#202536' }" :row-style="{ color: '#5E617D' }"
                          @selection-change="handleSelectionChange">
                    <!-- <el-table-column type="selection" /> -->
                    <el-table-column type="index" label="序号"/>
                    <el-table-column prop="serveCompanyName" label="派遣单位名" width="200px"/>
                    <el-table-column prop="comboName" label="投保方案"/>
                    <el-table-column prop="policyPeopleCount" label="人数"/>
                    <el-table-column width="200px" prop="createTime" label="生效日期"/>
                    <el-table-column prop="amount" label="保费"/>
                    <el-table-column prop="insureRate" label="费率">
                        <template #default="scope" class="operation">
                            +{{ scope.row.insureRate * 100 }}%
                        </template>
                    </el-table-column>
                    <el-table-column prop="createUserName" label="投保发起人">
                    </el-table-column>
                    <el-table-column prop="createPort" label="投保方式">
                        <template #default="scope" class="operation">
                            {{ scope.row.createPort === 1 ? 'PC投保' : '手机投保' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template #default="scope" class="operation">
                            <p style="color:#1989FA;float:left;" class="point" @click="
                                $router.push({
                                    path: '/insure/deduction/detail/' + scope.row.id
                                })
                                ">
                                查看详情
                            </p>
                            <p style="color:#1989FA;margin-left:65px" class="point"
                               @click="onSingleExport(scope.row.id)">
                                导出
                            </p>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination class="pagination" v-model:currentPage="pageNum" v-model:page-size="pageSize"
                               :page-sizes="[10, 30, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                               :total="total"
                               @size-change="handleSizeChange" @current-change="insureDeductionList">
                </el-pagination>
            </div>
        </el-tabs>
        <batch-insure-vue v-if="isInsure" @complete="insureComplete" @close="onCloseCallback"/>
    </div>
    <!-- 不在提供 到达 insure-company 页面的方法  insure-company -->
    <div>
        <insureCompany ref="insureCompany"></insureCompany>
    </div>
    <!-- 充值方法 -->
    <popupRecharge v-if="isRecharge" @close="onClose" useWay="InsureRechargeGsc" :openBank="openBank" :bankNo="bankNo"
                   :bankName="bankName" @determine="onDetermine" dataTitle="日日保充值"></popupRecharge>
    <!--    <div class="tc" @click.prevent="showtcflag = false" v-if="showtcflag">-->
    <div class="tc" @click.prevent="showtcflag = false" v-if="false">
        <div class="tcbox">
            <div class="tccontent">
                <div class="top">
                    <div></div>
                    <div @click="closetc">
                        <img src="../assets/closetwo.png" alt=""/>
                    </div>
                </div>
                <div class="bac2"></div>
                <div class="ctbox">
                    <div class="tctext">
                        <div class="ctop">
                            <img src="../assets/block.png" alt=""/><span class="text">日日保接口升级通知</span>
                        </div>
                        <p class="p" style="margin-top: 10px;">
                            当自<span class="boxshadle">2023年9月8日</span>起，日日保针对以下省份不再提供投保服务:
                        </p>
                        <div class="city">
                            北京、福建、甘肃、湖北、湖南、江苏、山东、陕西、四川、浙江
                        </div>
                        <p class="p" style="margin-top: 10px;">
                            预计恢复时间
                            <span class="boxshadle"> 9月底</span>
                            ;我们为您提供了其他的投保解决方案，具体可到对接群联系相关销售同事!
                        </p>
                    </div>
                    <div class="tcbtnbox">
                        <div class="btn" @click="closetc">我知道了</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import insureCompany from './insure-company.vue'
import {
    insureDeductionExport,
    insureDeductionDetailExport,
    insuranceDetailedExport
} from '@/api/export'
import store from '@/store/index'
import {
    insureDeduction,
    insureDeductionDetailListDto,
    insuranceRecharge,
    insureBalance,
    checkStatusWesure
} from '@/api/insure-deduction'
import batchInsureVue from '@/components/batch-insure.vue'
import user from '@/utils/user'
import axios from 'axios'
import { downLoadFile } from '../utils/util'
import popupRecharge from '@/components/popup-recharge.vue'
import { ElMessage } from 'element-plus'
import { getUserInfo, getqueryreceiptaccountapi } from '@/api/base'

export default defineComponent({
    name: 'InsureDeduction',
    components: {
        batchInsureVue,
        popupRecharge,
        insureCompany
    },
    data() {
        return {
            showtcflag: false,
            projectTime: '',
            pageSize: 10,
            pageNum: 1,
            total: 0 as number,
            tableData: [] as insureDeductionDetailListDto[],
            searchText: '',
            selects: [] as string[],
            insureCount: {} as {
                amount: number;
                insureProjectCount: number;
                policyPeopleCount: number;
            },
            isGsc: false,
            isInsure: false,
            isRecharge: false,
            openBank: '',
            bankNo: '',
            bankName: '',
            balanceObj: {} as any,
            canttb: false,
            showNotice: true
        }
    },
    async created() {
        console.log(user.isForbidInsure, 'user.isForbidInsure')
        user.waitLogin().then(() => {
            this.isGsc = user.isGsc
        })
        const data: any = await getUserInfo()
        const res: any = await getqueryreceiptaccountapi({ productType: 2 })
        console.log(res, 'hasfgsyfsuyguysgh')
        this.openBank = res.openBank
        this.bankNo = res.bankNo
        this.bankName = res.bankName
        console.log(data.isForbidInsure, 'datadtaat')
        sessionStorage.setItem(
            'dayinsuretcflag',
            JSON.stringify(data.isForbidInsure)
        )
        this.canttb = data.isForbidInsure
        if (sessionStorage.getItem('dayinsuretcflag') === 'true') {
            this.showtcflag = true
        } else {
            this.showtcflag = false
        }
        this.insureDeductionList()
        this.getInsureBalance()
    },
    methods: {
        closetc() {
            this.showtcflag = false
            sessionStorage.setItem('dayinsuretcflag', 'true')
        },
        daycz() {
            if (this.balanceObj.isOpenWesure === 1) {
                this.isRecharge = true
            } else {
                ElMessage({
                    type: 'warning',
                    message: '温馨提示：您还没有开通该功能权限，如有需要请联系销售'
                })
            }
        },
        // 检测是否可以批量投保
        cantonCheckStatusWesure() {
            this.showtcflag = true
        },
        async onCheckStatusWesure() {
            const result = await checkStatusWesure()
            console.log(result, 'result')
            if (!result.status) {
                this.$message.error(result.msg)
                return
            }
            this.isInsure = true
        },
        // 获取余额信息
        async getInsureBalance() {
            const result = await insureBalance({
                insureCompanyType: 'insure002_gsc'
            })
            this.balanceObj = result
            console.log(result, '')
        },
        async insureDeductionList() {
            const result = await insureDeduction({
                beginCreateTime: this.projectTime ? this.projectTime[0] : '',
                endCreateTime: this.projectTime ? this.projectTime[1] : '',
                searchText: this.searchText,
                pageSize: this.pageSize,
                pageNum: this.pageNum,
                insureCompanyType: 'insure002_gsc'
            })
            this.total = result.totalCount
            this.tableData = result.list
            this.insureCount = result.insureCount
        },
        handleSizeChange() {
            this.pageNum = 1
            this.insureDeductionList()
        },
        search() {
            this.pageNum = 1
            this.insureDeductionList()
        },
        onReset() {
            this.searchText = ''
            this.search()
        },
        handleSelectionChange(selects: { id: string }[]) {
            this.selects = selects.map(item => item.id)
            console.log(this.selects, 'selects')
        },
        /**
         * 导出勾选
         */
        async onExport() {
            console.log('导出了')
            const result = await insureDeductionExport(
                {
                    beginCreateTime: this.projectTime ? this.projectTime[0] : '',
                    endCreateTime: this.projectTime ? this.projectTime[1] : '',
                    searchText: this.searchText,
                    insureCompanyType: 'insure002_gsc'
                },
                {
                    loading: true
                }
            )
            if (!result.fileUrl && result.exportStatus === 0) {
                store.commit('getLongPollingFile', result)
            } else {
                axios({
                    url: result.fileUrl,
                    method: 'GET',
                    responseType: 'blob'
                }).then(async response => {
                    await downLoadFile(
                        response,
                        result.exportType,
                        result.updateTime,
                        result.remark
                    )
                    await this.$message.success('导出成功！')
                })
            }
            // window.location.href =
            //     process.env.VUE_APP_BASE_URL +
            //     '/common/download?delete=true&fileName=' +
            //     result

            // this.$message.success('导出成功！')
        },
        async onSingleExport(id: string) {
            console.log(id, 'id', this.selects, 'selects')
            const result = await insureDeductionDetailExport({
                ids: this.selects.toString() || id
            })

            window.location.href =
                process.env.VUE_APP_BASE_URL +
                '/common/download?delete=true&fileName=' +
                result

            this.$message.success('导出成功！')
        },
        async onExportDetail() {
            const result = await insuranceDetailedExport(
                {
                    beginCreateTime: this.projectTime ? this.projectTime[0] : '',
                    endCreateTime: this.projectTime ? this.projectTime[1] : '',
                    searchText: this.searchText,
                    insureCompanyType: 'insure002_gsc'
                },
                {
                    loading: true
                }
            )
            if (!result.fileUrl && result.exportStatus === 0) {
                store.commit('getLongPollingFile', result)
            } else {
                axios({
                    url: result.fileUrl,
                    method: 'GET',
                    responseType: 'blob'
                }).then(async response => {
                    await downLoadFile(
                        response,
                        result.exportType,
                        result.updateTime,
                        result.remark
                    )
                    await this.$message.success('导出成功！')
                })
            }
            // window.location.href =
            //     process.env.VUE_APP_BASE_URL +
            //     '/common/download?delete=true&fileName=' +
            //     result

            // this.$message.success('导出成功！')
        },
        insureComplete() {
            this.isInsure = false
            this.handleSizeChange()
        },
        onCloseCallback() {
            this.isInsure = false
        },
        // 关闭弹窗
        onClose() {
            this.isRecharge = false
        },
        // 充值弹窗点击确定关闭
        async onDetermine(num: string, ocrNum: string, ocrImg: string, isRepeat: boolean) {
            if (!num) {
                this.$message.error('请输入金额')
                return
            }
            if (!ocrImg) {
                this.$message.error('请上传凭证')
                return
            }
            // fileName = fileName.split('base64,')[1]
            const result = await insuranceRecharge({
                rechargeAmount: num,
                ocrAmount: ocrNum,
                voucherUrl: ocrImg,
                receiptId: user.receiptId,
                isRepeat: isRepeat
            })
            if (result) {
                // this.isRecharge = false
                this.$message.success('提交成功')
            }
        },
        // 在insure-deduction页面调用insure-company页面的 方法 使用 ref
        onDialogVisible() {
            let dialogVisible = '' as any
            dialogVisible = this.$refs
            dialogVisible.insureCompany.onOpenDialogVisible()
        }
    }
})
</script>

<style lang="stylus" scoped>
table()
.header-box
    display grid
    grid-template-columns repeat(3, 1fr)
    grid-gap 16px
    margin-top 24px

    .block
        padding 0
        width: 100%
        margin-top 0

    .block-header
        space-between(false)
        border-bottom 1px solid #F7F8FC
        padding 14px 16px 8px

    .block-header-active
        padding 16px 16px 9px 16px

    .block-title
        font-size font-small
        color black
        font-weight bold

    .block-more
        display flex
        align-items center
        color color-blue

        .triangle
            margin-left 8px
            border-color color-blue transparent transparent transparent
            transform rotate(270deg)
            top 0

    .block-content
        // space-between()
        padding 18px 16px

        .number
            color #202536
            font-size 26px
            font-weight bold

    .block-content-active
        padding 28px 26px

.screen-box
    margin-top 24px

.header.block {
    padding 20px
}

.header
    space-between()

.basic
    margin-top 20px

.value
    margin-right 30px

.value.important
    color color-red
    font-style italic

:deep().el-tabs__header.is-top
    display inline-block
    margin-top -20px

:deep().el-tabs__nav-scroll
    padding-right 20px

.download-btn
    width: 126px !important;

.btn-red
    background: #FF7E68

.el-tabs__header
    margin: 0

.block-alone
    padding: 0 24px 0

.header-info-box
    padding-bottom 16px
    box-sizing border-box
    border-bottom 1px solid #F4F4F7

    .title
        font-size 16px
        font-weight 600
        color #3D3D3D

.insure-record
    display flex
    color #202536
    font-size 16px

    .record-i
        margin-left 44px

    .num
        color #FF7E68

.search .btn-alone
    width 120px
    background #1989FA
    color #fff

.dispatch-icon
    width 16px
    height 16px
    margin-right 10px

.recharge-btn
    border-radius 20px
    margin-top 16px
    margin-bottom 0
    width 76px

.nav-item
    display flex
    flex-direction column
    align-items center

.icon-img
    margin-bottom 15px
    width 60px
    height 31px

.decline-img
    width 16px
    height 16px
    margin-right 4px

.compare-box
    margin-top 29px

.tc
    z-index 9999999
    overflow auto
    width 100vw
    height 100vh
    position fixed
    top 0
    left 0
    background-color rgba(91, 91, 91, 0.8)
    display flex
    align-items center
    justify-content center

.tctext
    background-color #D6F6E9
    width 100%
    min-height 100px
    margin-top 0
    box-sizing border-box
    border-radius 8px
    margin-bottom 16px
    box-sizing border-box
    padding 24px

    .p
        font-size 14px
        color #20362B
        margin 0

    .city {
        width 100%
        background-color #EBFBF4
        border-radius 8px
        margin-top 10px
        padding 6px
        font-size 14px
    }

    .ctop
        display flex
        align-items center

        .text
            display inline-block
            margin-left 8px
            color #00C271
            font-size 20px
            font-weight 800

.ctbox
    margin-top -120px

.bac2
    width 100%
    height 225px
    background-image url(../assets/bac3.png)
    background-repeat no-repeat
    background-size 100%
    transform translateY(-60px)

.tcbox
    width 665px
    height 550px

.tccontent
    position relative
    overflow initial
    font-size 16px
    box-sizing border-box
    padding 0 40px
    width 100%
    height 370px
    background-image url(../assets/bg.png)
    background-repeat no-repeat
    background-size 100%
    border-radius 8px

.top
    position absolute
    width 100%
    height 50px
    display flex
    align-items center
    justify-content space-between
    top -80px
    left -5px

.tcbtnbox
    width 100%
    box-sizing border-box
    display flex
    align-items center
    justify-content center

    .btn
        background-color #00D679
        font-size 14px
        color #FFFFFF
        width 112px
        height 32px
        border-radius 16px
        text-align center
        line-height 32px

.boxshadle
    color #20362B
    font-weight bold
    position relative
    z-index 999999999

    &::after
        display block
        content ''
        background linear-gradient(90deg, #E7F8F1 0%, #99F9D1 54%, #E7F8F1 100%)
        width 100%
        height 10px
        position absolute
        bottom 0
        left 0
        z-index -9
</style>
